package org.learn;

import io.netty.buffer.ByteBufUtil;
import org.apache.commons.lang.ArrayUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.Socket;
import java.nio.ByteBuffer;


//luohao_tag TCP    CLIENT
public class TcpClient {

    private static byte[] rocketProtocol() throws UnsupportedEncodingException {

        String lines = "{\"name\":\"luohao\",\"code\":103}";
        byte[] length = ByteBuffer.allocate(4).putInt(lines.length()).array();
        byte[] outputBytes = lines.getBytes("UTF-8");
        return ArrayUtils.addAll(length,outputBytes);

    }

    private static byte[] rocketAllName() throws UnsupportedEncodingException {

        String lines = "{\"name\":\"luohao\",\"code\":206}";
        byte[] length = ByteBuffer.allocate(4).putInt(lines.length()).array();
        byte[] outputBytes = lines.getBytes("UTF-8");
        return ArrayUtils.addAll(length,outputBytes);
    }


    private static byte[] json() throws UnsupportedEncodingException {
        String lines = "{\"name\":\"luohao\",\"code\":206}";
        return lines.getBytes("UTF-8");
    }


	public static void main(String[] args) throws IOException {
		Socket socket = null;
        OutputStream out = null;
        InputStream in = null;
  
        try {

            socket = new Socket("localhost", 9876);
            out = socket.getOutputStream();  


            // 请求服务器  
//            String lines = "床前明月光\r\n疑是地上霜\r\n举头望明月\r\n低头思故乡\r\n";


//            byte [] data =rocketProtocol();
//            byte [] data =rocketAllName();
            byte [] data =json();

            out.write(data);
            out.flush();
            in = socket.getInputStream();
            int a ;
            int j =0;
            while ((a = in.read()) != -1){
                System.err.println(a);
                j++;
                if(j>100)
                    break;
            }
  
        } finally {  
            // 关闭连接  
            out.close();
            in.close();
            socket.close();  
        }  

	}

}